/*
 * ENUM Discoverer. ENUM Demonstration software, demonstrating the potential of ENUM.
 * 
 * Copyright (C) 2009 SIDN and ISOC.nl
 * 
 * This file is part of ENUM Discoverer.
 *
 * ENUM Discoverer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ENUM Discoverer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ENUM Discoverer.  If not, see <http://www.gnu.org/licenses/>.
 */

package nl.sidn.enumdiscoverer.contacts.adapters;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.spikylee.hyves4j.H4jException;
import com.spikylee.hyves4j.Hyves4j;
import com.spikylee.hyves4j.client.H4jClient;
import com.spikylee.hyves4j.client.config.H4jClientConfig;
import com.spikylee.hyves4j.interfaces.users.H4jUsers;
import com.spikylee.hyves4j.model.City;
import com.spikylee.hyves4j.model.Country;
import com.spikylee.hyves4j.model.Image;
import com.spikylee.hyves4j.model.ProfilePicture;
import com.spikylee.hyves4j.model.User;
import com.spikylee.hyves4j.model.User.Birthday;

import android.util.Log;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthServiceProvider;
import nl.sidn.enumdiscoverer.EnumRecord;
import nl.sidn.enumdiscoverer.LogConfig;
import nl.sidn.enumdiscoverer.WebLinkConstants;
import nl.sidn.enumdiscoverer.contacts.ContactProfileAggregator;

/**
 * 
 * @author  Miroslav Vujičić (miroslav@catalyst.net.nz)
 * @author	Grant Patterson (grant.patterson@catalyst.net.nz)
 */
public class HyvesAdapter extends WebLinkAdapter {

	static final String TAG = LogConfig.getLogTag(HyvesAdapter.class);
	// whether DEBUG level logging is enabled (whether globally, or explicitly for this log tag)
	static final boolean DEBUG = LogConfig.isDebug(TAG);
	// whether VERBOSE level logging is enabled
	static final boolean VERBOSE = LogConfig.VERBOSE;
	
	public HyvesAdapter() {
		super(WebLinkConstants.HYVES);
	}

	@Override
	public void updateContact(String urlCapture, EnumRecord enumRecord,
			ContactProfileAggregator profileAggregator) {
		// let the parent class do whatever it wants to with the information
		super.updateContact(urlCapture, enumRecord, profileAggregator);
		
		// Update contact with whatever information is retrieved from Hyves
		
		if (VERBOSE) Log.v(TAG, "urlCapture = " + urlCapture);
		if (VERBOSE) Log.v(TAG, "URL = " + enumRecord.getUrl());
		
		User user = getHyvesUser(urlCapture);
		
		if (user == null) {
			return;
		}
		
		profileAggregator.addName(getName(user), enumRecord);
		profileAggregator.addAddress(getAddress(user), enumRecord);
		profileAggregator.addNickName(user.getNickName(), enumRecord);
		profileAggregator.addDateOfBirth(getDateOfBirth(user), enumRecord);
		profileAggregator.addPhoto(getPhotoUrl(user), enumRecord);
		profileAggregator.addStatus(user.getOnMyMind(), enumRecord);
	}

	private static User getHyvesUser(String name) {
		try {
			String requestTokenURL = "http://data.hyves-api.nl/";
			String accessTokenURL = "http://www.hyves.nl/api/authorize/";
			String userAuthorizationURL = "http://data.hyves-api.nl/";

			OAuthServiceProvider serviceProvider = new OAuthServiceProvider(requestTokenURL, userAuthorizationURL, accessTokenURL);

			String consumerKey = "NDM0MF90TqG4siXPX55Iz7x-H6J_";
			String consumerSecret = "NDM0MF9QtOc7qxm5pecWR0QtcNmP";
			
			OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, serviceProvider);
			String consumerName = "enum-discoverer";
			H4jClientConfig config = new H4jClientConfig(consumerName);

			String accessToken = "YXRfMTAwMTE3NDk3X5rbg3g6XFhqiicmhfsoP_s=";
			config.setAccessToken(accessToken);
			String tokenSecret = "fqt57uzCteMcMejbCQXIbw==";
			config.setTokenSecret(tokenSecret);

			H4jClient client = new H4jClient(config, consumer);
			Hyves4j h4j = new Hyves4j(client);
			H4jUsers users = h4j.getUsers();
			User user = users.getByUsername(name, true, true, true, false, true);
			
			if (DEBUG) Log.d(TAG, "Retrieved user " + user.getFirstName() + " " + user.getLastName());
			
			return user;
			
		} catch (H4jException e) {
			
			Log.w("Error retrieving user from Hyves", e);
			return null;
		}
	}
	
	private static String getName(User user) {
		
		String firstname = user.getFirstName();
		String lastname = user.getLastName();
		
		if (lastname != null && firstname != null) {
			return firstname + " " + lastname;
		} else if (firstname != null) {
			return firstname;
		} else if (lastname != null) {
			return lastname;
		} else {
			return null;
		}
	}
	
	private static String getAddress(User user) {
		
		String address = "";
		
		City city = user.getCity();
		Country country = user.getCountry();
		
		if (city != null && city.getName() != null) {
			address += city.getName();
		}
		
		if (country != null && country.getName() != null) {
			
			if (address.length() != 0) {
				address += "\n";
			}
			address += country.getName();
		}
		
		return address.length() > 0 ? address : null;
	}
	
	private static Date getDateOfBirth(User user) {
		
		Birthday bday = user.getBirthday();
		if (bday == null) return null;
		
		Calendar cal = new GregorianCalendar(bday.getYear(), bday.getMonth(), bday.getDay());
		
		return cal == null ? null : cal.getTime();
	}
	
	private static String getPhotoUrl(User user) {
		
		ProfilePicture photo = user.getProfilePicture();
		if (photo == null) return null;
		
		Image medium = photo.getLargeIcon();
		
		return medium == null ? null : medium.getSource();
	}
	
}
